package com.dgut.epidemic.service;

import com.dgut.epidemic.mapper.UserMapper;
import com.dgut.epidemic.pojo.MyUserDetails;
import com.dgut.epidemic.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author: wuhaoduan
 * Date: 2021/6/4 17:02
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    //获得用户姓名
    @Override
    public String getUserNameById(int id){
        return userMapper.getUserName(id);
    }

    @Override
    public User getUserNow() {
        MyUserDetails activeUser = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user =  userMapper.getUserNowByUserName(activeUser.getUsername());
        user.setPassword(user.getPassword().substring(6));
        return user;
    }

    //更新管理员密码
    @Override
    public void updateAdmin(User user) {
        user.setPassword("{noop}" + user.getPassword());
        userMapper.updateUser(user);
    }

    @Override
    public int insertUser(User user) {
        //用户名已存在
        if(userMapper.judgeUserNameIsExist(user.getUsername()) == 1)
            return 1;
        user.setPassword("{noop}" + user.getPassword());
        userMapper.insertUser(user);
        return 0;
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public void deleteUser(String id) {
        userMapper.deleteUser(id);
    }
}
